package com.codeduck.mock.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author: <a href="mailto:codeduck@163.com">codeduck</a>
 * @date: 2023/01/07
 */
@Service
public class HealthCheckService {

    private static final String SQL = "select 1 from dual";

    public int dbCheck() {
        int flag = 0;
        Connection connection = null;
        Statement statement = null;
        ResultSet rs = null;
        try {
            InitialContext ctx = new InitialContext();
            DataSource dataSource = (DataSource) ctx.lookup("hello");
            connection = dataSource.getConnection();
            statement = connection.createStatement();

            for (rs = statement.executeQuery(SQL); rs.next(); flag = 0) {
            }
        } catch (NamingException e) {
            flag = -1;
            e.printStackTrace();
        } catch (SQLException e) {
            flag = -1;
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                flag = -1;
                e.printStackTrace();
            }
        }
        return flag;
    }

    public int fsCheck() {
        File file = new File("hello.txt");
        FileWriter fw = null;
        BufferedWriter bw = null;
        int flag = 0;
        try {
            if (file.exists()) {
                file.delete();
            }
            fw = new FileWriter(file);
            bw = new BufferedWriter(fw);
            bw.write("hello world!");
        } catch (IOException e) {
            flag = -1;
            e.printStackTrace();
        } finally {
            try {
                if (bw != null) {
                    bw.close();
                }
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException e) {
                flag = -1;
                e.printStackTrace();
            }
        }
        return flag;
    }
}
